import React, { useState, useRef, useEffect } from "react";
import "./style.css";

// 高阶组件： 本身是一个函数， 该函数接受一个组件作为参数， 并且返回一个组件。这个函数我们叫做高阶组件
// 高阶并不是React的语法，只是根据React特性，进行代码复用的一种编程思维，一种高级技巧。

const withDrag = (Comp) => {
  return () => {
    const onTouchStart = (e) => {
      const touch = e.changedTouches[0];  
      setPos({
        x: touch.clientX - ref.current.offsetLeft,
        y: touch.clientY - ref.current.offsetTop,
      });
      setLeft(ref.current.offsetLeft);
      setTop(ref.current.offsetTop);
      setisMove(true);
    };
    const onTouchMove = (e) => {
      const touch = e.changedTouches[0];
      if (isMove) {
        setLeft(touch.clientX - pos.x);
        setTop(touch.clientY - pos.y);
      }
    };
    const onTouchEnd = (e) => {
      setisMove(false);
    };
    const [pos, setPos] = useState({
      x: 0,
      y: 0,
    });
    const ref = useRef();
    const [isMove, setisMove] = useState(false);
    const [left, setLeft] = useState(0);
    const [top, setTop] = useState(0);

    useEffect(() => {
      setLeft(ref.current.offsetLeft);
      setTop(ref.current.offsetTop);
      setTimeout(() => {
        ref.current.style.position = "fixed";
      }, 0);
    }, []);
    return (
      <div
        style={{ left: left, top: top }}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
        ref={ref}
      >
        <Comp></Comp>
      </div>
    );
  };
};

const CompA = () => {
  return (
    <div style={{ width: 100, height: 200, background: "red" }}>
      大家好才是真的好
    </div>
  );
};
const CompB = () => {
  return (
    <div style={{ width: 100, height: 200, background: "skyblue" }}>
      大家好才是真的好
    </div>
  );
};

const CompADrag = withDrag(CompA);
const CompBDrag = withDrag(CompB);

const Index = () => {
  return (
    <div>
      <div>首页</div>
      <CompADrag></CompADrag>

      <CompBDrag></CompBDrag>
    </div>
  );
};

export default Index;
